package com.taorenqi.business.fragment.mine;


import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.taorenqi.business.R;
import com.taorenqi.business.app.MyApp;
import com.taorenqi.business.event.RechargeEvent;
import com.taorenqi.business.fragment.base.BaseBackFragment;
import com.taorenqi.business.helper.payment.AliPayUtils;
import com.taorenqi.business.utils.Encoder;
import com.taorenqi.business.utils.StringUtils;
import com.taorenqi.business.utils.ToastUtil;
import com.taorenqi.business.widget.statusview.StatusView;
import com.taorenqi.business.widget.subscribers.PageDataSubscriberOnNext;
import com.taorenqi.business.widget.subscribers.ProgressSubscriber;
import com.taorenqi.data.common.BasePageableResponse;
import com.taorenqi.data.entity.payment.AliPayResponseEntity;
import com.taorenqi.data.service.PaymentDataHttpRequest;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static java.lang.Integer.parseInt;

/**
 * vip充值页面
 * A simple {@link Fragment} subclass.
 */
public class VipFragment extends BaseBackFragment implements RadioGroup.OnCheckedChangeListener {


    @Bind(R.id.status_view)
    StatusView statusView;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.et_buy_vip_num)
    EditText etBuyVipNum;
    @Bind(R.id.tv_buy_vip_nine)
    CheckBox tvBuyVipNine;
    @Bind(R.id.tv_buy_vip_twelve)
    CheckBox tvBuyVipTwelve;
    @Bind(R.id.tv_buy_vip_twentyfour)
    CheckBox tvBuyVipTwentyfour;
    @Bind(R.id.tv_buy_vip_compara)
    TextView tvBuyVipCompara;
    @Bind(R.id.iv_buy_vip_pay_icon)
    ImageView ivBuyVipPayIcon;
    @Bind(R.id.iv_buy_vip_pay_name)
    TextView ivBuyVipPayName;
    @Bind(R.id.ll_buy_vip_pay)
    LinearLayout llBuyVipPay;
    @Bind(R.id.tv_buy_vip_primary_price)
    TextView tvBuyVipPrimaryPrice;
    @Bind(R.id.tv_buy_vip_now_price)
    TextView tvBuyVipNowPrice;
    @Bind(R.id.tv_buy_vip_now_price_mouth)
    TextView tvBuyVipNowPriceMouth;
    @Bind(R.id.tv_buy_vip_commit)
    TextView tvBuyVipCommit;
    @Bind(R.id.activity_buy_vip)
    LinearLayout activityBuyVip;
    @Bind(R.id.vip_ll)
    LinearLayout vipLl;

    private RadioButton rbAlipay;
    private RadioButton rbWechatpay;
    private RadioButton rbYibaopay;
    private RadioGroup rgPay;
    private Dialog dialog;
    private Dialog dialog_pay;
    private int pay = 0;
    private int number;

    private BasePageableResponse<AliPayResponseEntity> data;
    private PageDataSubscriberOnNext<BasePageableResponse<AliPayResponseEntity>> aliPaySubscriber;

    public static VipFragment newInstance() {
        // Required empty public constructor
        VipFragment fragment = new VipFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_vip, container, false);
        ButterKnife.bind(this, view);
        toolbar.setTitle("升级VIP");
        initToolbarNav(toolbar);
        initPay(pay);
        initHttpRequestData();
        initData();
        return view;
    }

    private void initData() {
        etBuyVipNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                if (editable.length() >= 1) {

                    int i = parseInt(editable.toString());
                    int price = i * 100;
                    if (i < 9 && i >= 3) {
                        tvBuyVipPrimaryPrice.setText(price + "");
                        tvBuyVipPrimaryPrice.setBackgroundResource(R.color.white);
                        vipLl.setVisibility(View.GONE);
                        tvBuyVipNowPrice.setVisibility(View.INVISIBLE);
                        tvBuyVipNowPrice.setText(price + "");
                        tvBuyVipNowPriceMouth.setVisibility(View.INVISIBLE);
                    } else if (i >= 9 && i < 12) {
                        vipLl.setVisibility(View.VISIBLE);
                        tvBuyVipNowPrice.setVisibility(View.VISIBLE);
                        tvBuyVipNowPriceMouth.setVisibility(View.VISIBLE);
                        tvBuyVipPrimaryPrice.setBackgroundResource(R.mipmap.crossedout);
                        tvBuyVipPrimaryPrice.setText(price + "");
                        tvBuyVipNowPrice.setText(price * 0.9 + "");
                        tvBuyVipNowPriceMouth.setText("元(90/月)");

                    } else if (i >= 12 && i < 24) {
                        vipLl.setVisibility(View.VISIBLE);
                        tvBuyVipNowPrice.setVisibility(View.VISIBLE);
                        tvBuyVipNowPriceMouth.setVisibility(View.VISIBLE);
                        tvBuyVipPrimaryPrice.setBackgroundResource(R.mipmap.crossedout);
                        tvBuyVipPrimaryPrice.setText(price + "");
                        tvBuyVipNowPrice.setText(price * 0.8 + "");
                        tvBuyVipNowPriceMouth.setText("元(80/月)");
                    } else if (i >= 24) {
                        vipLl.setVisibility(View.VISIBLE);
                        tvBuyVipNowPrice.setVisibility(View.VISIBLE);
                        tvBuyVipNowPriceMouth.setVisibility(View.VISIBLE);
                        tvBuyVipPrimaryPrice.setBackgroundResource(R.mipmap.crossedout);
                        tvBuyVipPrimaryPrice.setText(price + "");
                        tvBuyVipNowPrice.setText(price * 0.75 + "");
                        tvBuyVipNowPriceMouth.setText("元(75/月)");
                    } else {
                        Toast.makeText(_mActivity, "最低开通3个月", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    tvBuyVipPrimaryPrice.setText("0");
                    tvBuyVipPrimaryPrice.setBackgroundResource(R.color.white);
                    tvBuyVipNowPrice.setVisibility(View.INVISIBLE);
                    tvBuyVipNowPriceMouth.setVisibility(View.INVISIBLE);

                }
            }
        });
    }

    private void initHttpRequestData() {

        aliPaySubscriber = new PageDataSubscriberOnNext<BasePageableResponse<AliPayResponseEntity>>() {
            @Override
            public void onNext(BasePageableResponse<AliPayResponseEntity> entity) {
                //接口请求成功后处理,调起微信支付。
                data = entity;
                AliPayUtils.getInstant(_mActivity).pay(entity);
                EventBus.getDefault().post(new RechargeEvent());
            }
        };
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void initPay(int pay) {
        ivBuyVipPayIcon.setVisibility(View.VISIBLE);
        ivBuyVipPayName.setVisibility(View.VISIBLE);
        switch (pay) {
            case 0:
                ivBuyVipPayIcon.setVisibility(View.INVISIBLE);
                ivBuyVipPayName.setVisibility(View.INVISIBLE);
                break;
            case 1:
                ivBuyVipPayIcon.setImageResource(R.mipmap.zhifubao_icon);
                ivBuyVipPayName.setText("支付宝");
                break;
            case 2:
                ivBuyVipPayIcon.setImageResource(R.mipmap.weixingzhifu_icon);
                ivBuyVipPayName.setText("微信支付");
                break;
            case 3:
                ivBuyVipPayIcon.setImageResource(R.mipmap.yibaozhifu_icon);
                ivBuyVipPayName.setText("易宝支付");
                break;
        }

    }

    @OnClick({R.id.tv_buy_vip_nine, R.id.tv_buy_vip_twelve, R.id.tv_buy_vip_twentyfour,
            R.id.ll_buy_vip_pay, R.id.tv_buy_vip_commit, R.id.tv_buy_vip_compara})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_buy_vip_nine:
                tvBuyVipNine.setChecked(true);
                tvBuyVipTwelve.setChecked(false);
                tvBuyVipTwentyfour.setChecked(false);
                isCheck(tvBuyVipNine);
                isCheck(tvBuyVipTwelve);
                isCheck(tvBuyVipTwentyfour);

                tvBuyVipNine.setChecked(false);
                tvBuyVipTwelve.setChecked(true);
                tvBuyVipTwentyfour.setChecked(true);

                int price_9 = 900;
                etBuyVipNum.getText().clear();
                tvBuyVipNowPrice.setVisibility(View.VISIBLE);
                tvBuyVipNowPriceMouth.setVisibility(View.VISIBLE);
                tvBuyVipPrimaryPrice.setBackgroundResource(R.mipmap.crossedout);
                tvBuyVipPrimaryPrice.setText(price_9 + "");
                tvBuyVipNowPrice.setText(price_9 * 0.9 + "");
                tvBuyVipNowPriceMouth.setText("元(90/月)");

                etBuyVipNum.setText("9");

                break;
            case R.id.tv_buy_vip_twelve:
                tvBuyVipTwelve.setChecked(true);
                tvBuyVipNine.setChecked(false);
                tvBuyVipTwentyfour.setChecked(false);
                isCheck(tvBuyVipNine);
                isCheck(tvBuyVipTwelve);
                isCheck(tvBuyVipTwentyfour);

                tvBuyVipNine.setChecked(true);
                tvBuyVipTwelve.setChecked(false);
                tvBuyVipTwentyfour.setChecked(true);

                int price_12 = 1200;
                etBuyVipNum.getText().clear();
                tvBuyVipNowPrice.setVisibility(View.VISIBLE);
                tvBuyVipNowPriceMouth.setVisibility(View.VISIBLE);
                tvBuyVipPrimaryPrice.setBackgroundResource(R.mipmap.crossedout);
                tvBuyVipPrimaryPrice.setText(price_12 + "");
                tvBuyVipNowPrice.setText(price_12 * 0.8 + "");
                tvBuyVipNowPriceMouth.setText("元(80/月)");

                etBuyVipNum.setText("12");

                break;
            case R.id.tv_buy_vip_twentyfour:
                tvBuyVipTwentyfour.setChecked(true);
                tvBuyVipNine.setChecked(false);
                tvBuyVipTwelve.setChecked(false);
                isCheck(tvBuyVipNine);
                isCheck(tvBuyVipTwelve);
                isCheck(tvBuyVipTwentyfour);

                tvBuyVipNine.setChecked(true);
                tvBuyVipTwelve.setChecked(true);
                tvBuyVipTwentyfour.setChecked(false);

                int price_24 = 2400;
                etBuyVipNum.getText().clear();
                tvBuyVipNowPrice.setVisibility(View.VISIBLE);
                tvBuyVipNowPriceMouth.setVisibility(View.VISIBLE);
                tvBuyVipPrimaryPrice.setBackgroundResource(R.mipmap.crossedout);
                tvBuyVipPrimaryPrice.setText(price_24 + "");
                tvBuyVipNowPrice.setText(price_24 * 0.8 + "");
                tvBuyVipNowPriceMouth.setText("元(75/月)");

                etBuyVipNum.setText("24");

                break;
            case R.id.tv_buy_vip_compara://显示对比内容
                showdialog_compara();
                break;
            case R.id.ll_buy_vip_pay://支付方式
                showdialog_pay();
                break;
            case R.id.tv_buy_vip_commit://确认支付

                if (StringUtils.isEmpty(etBuyVipNum.getText().toString().trim())) {
                    ToastUtil.showToast(_mActivity, "请输入开通的月数");
                } else {
                    number = Integer.parseInt(etBuyVipNum.getText().toString().trim());
                }


                switch (pay) {
                    case 0:
                        Toast.makeText(_mActivity, "选择支付方式", Toast.LENGTH_SHORT).show();
                        return;
                    case 1:
                        if (number < 3) {
                            ToastUtil.showToast(_mActivity, "最低开通三个月");
                        } else {
                            initAlipay();
                        }
                        break;
                    case 2:
                        ToastUtil.showToast(_mActivity, "微信支付开发中，请选择支付宝支付");
                        break;
                    case 3:
                        ToastUtil.showToast(_mActivity, "易宝支付开发中，请选择支付宝支付");
                        break;
                }


                break;
        }
    }

    private void initAlipay() {

        String attrNo = etBuyVipNum.getText().toString().trim();
        int type = pay;
        HashMap map = new HashMap();
        map.put("attrNo", attrNo);
        map.put("shop_bank", type + "");
        String sign = Encoder.getSigns(map);
        PaymentDataHttpRequest.getInstance(MyApp.getApp()).requestAliPayForVip(new ProgressSubscriber(aliPaySubscriber, _mActivity), attrNo, type, sign);
    }

    /**
     * 显示支付
     */
    private void showdialog_pay() {
        dialog_pay = new Dialog(_mActivity, R.style.my_dialog);
        dialog_pay.setCanceledOnTouchOutside(true);
        LinearLayout view = (LinearLayout) LayoutInflater.from(_mActivity).inflate(R.layout.compara_pay, null);
        rgPay = (RadioGroup) view.findViewById(R.id.rg_pay);
        rbAlipay = (RadioButton) view.findViewById(R.id.rb_alipay);
        rbWechatpay = (RadioButton) view.findViewById(R.id.rb_wechatpay);
        rbYibaopay = (RadioButton) view.findViewById(R.id.rb_yibaopay);


        rgPay.setOnCheckedChangeListener(this);

        dialog_pay.setContentView(view);
        Window dialogWindow = dialog_pay.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
//        dialogWindow.setWindowAnimations(R.style.dialogstyle);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        lp.x = 0; // 新位置X坐标
        lp.y = -20; // 新位置Y坐标
        //lp.y = getWindowManager().getDefaultDisplay().getHeight();; // 新位置Y坐标
        //lp.width = (int) getResources().getDisplayMetrics().widthPixels; // 宽度
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT; // 宽度
        view.measure(0, 0);
        //lp.height = view.getMeasuredHeight();
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        lp.alpha = 9f; // 透明度
        //dialogWindow.setAttributes(lp);
        dialogWindow.setAttributes(lp);
        dialog_pay.show();
    }

    /**
     * 显示对比内容
     */
    private void showdialog_compara() {
        dialog = new Dialog(_mActivity, R.style.my_dialog);
        dialog.setCanceledOnTouchOutside(true);
        LinearLayout view = (LinearLayout) LayoutInflater.from(_mActivity).inflate(R.layout.compara_dialog, null);
        view.findViewById(R.id.iv_compara_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.setContentView(view);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
//        dialogWindow.setWindowAnimations(R.style.dialogstyle);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        lp.x = 0; // 新位置X坐标
        lp.y = -20; // 新位置Y坐标
        //lp.y = getWindowManager().getDefaultDisplay().getHeight();; // 新位置Y坐标
        //lp.width = (int) getResources().getDisplayMetrics().widthPixels; // 宽度
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT; // 宽度
        view.measure(0, 0);
        //lp.height = view.getMeasuredHeight();
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        lp.alpha = 9f; // 透明度
        //dialogWindow.setAttributes(lp);
        dialogWindow.setAttributes(lp);
        dialog.show();
    }

    private void isCheck(CheckBox checkBox) {
        if (checkBox.isChecked()) {
            checkBox.setBackgroundColor(getResources().getColor(R.color.login_orange));
            checkBox.setTextColor(getResources().getColor(R.color.white));
        } else {
            checkBox.setBackgroundColor(getResources().getColor(R.color.comparaGray));
            checkBox.setTextColor(getResources().getColor(R.color.myText));
        }
    }

    Handler handler = new Handler();

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        if (checkedId == rbAlipay.getId()) {//支付宝支付
            pay = 1;
            initPay(pay);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    dialog_pay.dismiss();
                }
            }, 500);

        }
        if (checkedId == rbWechatpay.getId()) {//微信支付
            pay = 2;
            initPay(pay);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    dialog_pay.dismiss();
                }
            }, 500);
        }
        if (checkedId == rbYibaopay.getId()) {//易宝支付
            pay = 3;
            initPay(pay);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    dialog_pay.dismiss();
                }
            }, 500);
        }
    }
}
